package DataAccess;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import pojo.NguoiDungPOJO;
import pojo.TinNhanPOJO;

public class TinNhanDA extends BaseDA {

	public TinNhanPOJO get(int id) {
		TinNhanPOJO rs = null;
		String sql = "select * from TinNhan where id=" + id;

		try {
			ResultSet rss = provider.executeQuery(sql);
			while (rss.next()) {
				rs = getProperties(rss);
				break;
			}
		} catch (Exception e) {
			rs = null;
		}

		return rs;
	}

	public ArrayList<TinNhanPOJO> getByNguoiNhan(String nguoiNhan, int tinhTrang) {
		ArrayList<TinNhanPOJO> rs = null;
		String sql = "select * from tinnhan where nguoinhan='"+nguoiNhan+"' and tinhtrang="+tinhTrang;

		try {
			rs = new ArrayList<TinNhanPOJO>();
			ResultSet rss = provider.executeQuery(sql);
			while (rss.next()) {
				TinNhanPOJO tn = getProperties(rss);
				rs.add(tn);
			}
		} catch (Exception e) {
			rs = null;
		}

		return rs;
	}

	

	public int insert(TinNhanPOJO tinNhan) {
		int rs=-1;
		String procName = "spInsertTinNhan";
		String[] input = new String[] { tinNhan.getNguoiGui() + "", tinNhan.getNguoiNhan() + "",
				tinNhan.getNoiDung(),tinNhan.getLoai()+"" };
		try {
			ResultSet rss = provider.executeStore(procName, input);
			if (rss.next()) {
				
				rs= rss.getInt("ID");
				tinNhan.setId(rs);
			}
		} catch (Exception e) {
			rs =-1;
		}
		return rs;
	}

	public int soLuongOffline(int idNguoiDung) {
		String sql = "select count(*) as SoLuong from tinnhan where tinhtrang=0 and idNguoiNhan=" + idNguoiDung;
		int rs = 0;
		try {
			ResultSet rss = provider.executeQuery(sql);
			if (rss.next()) {
				rs = rss.getInt("SoLuong");
			}
		} catch (Exception e) {
			rs = 0;
		}
		return rs;
	}
	public int soLuongOffline(String nguoiDung) {
		String sql = "select count(*) as SoLuong from tinnhan where tinhtrang=0 and nguoinhan='" + nguoiDung+"'";
		int rs = 0;
		try {
			ResultSet rss = provider.executeQuery(sql);
			if (rss.next()) {
				rs = rss.getInt("SoLuong");
			}
		} catch (Exception e) {
			rs = 0;
		}
		return rs;
	}

	public boolean capNhatDaDoc(int id) {
		boolean rs = false;
		try {
			String sql = "update tinnhan set tinhtrang=1 where id=" + id;
			provider.executeUpdate(sql);
			rs = true;
		} catch (Exception e) {
			rs = false;
		}
		return rs;
	}
	

	@Override
	protected TinNhanPOJO getProperties(ResultSet rss) throws SQLException {
		TinNhanPOJO rs = new TinNhanPOJO();
		rs.setId(rss.getInt("ID"));
		rs.setNguoiGui(rss.getString("NguoiGui"));
		rs.setNguoiNhan(rss.getString("NguoiNhan"));
		rs.setNoiDung(rss.getString("NoiDung"));
		rs.setThoiGian(rss.getTimestamp("ThoiGian").getTime());
		rs.setTinhTrang(rss.getInt("TinhTrang"));
		rs.setLoai(rss.getInt("Loai"));
		return rs;
	}
}
